package com.ithuameng.cosy.handshake;

import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.QueryStringDecoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;

import java.util.List;

/**
 * websocket客户端握手请求信息
 * 用于在握手阶段鉴权
 *
 * @author ithuameng
 */
public class HandshakeEvent {

    private final String uri;

    private final HttpHeaders header;

    public HandshakeEvent(String uri, HttpHeaders header) {
        this.uri = uri;
        this.header = header;
    }

    public String getHeader(String name) {
        return header.get(name);
    }

    public List<String> getHeaders(String name) {
        return header.getAll(name);
    }

    public Integer getIntHeader(String name) {
        return header.getInt(name);
    }

    public String getParameter(String name) {
        QueryStringDecoder decoder = new QueryStringDecoder(uri);
        List<String> valueList = decoder.parameters().get(name);
        return valueList == null || valueList.isEmpty() ? null : valueList.get(0);
    }

    public List<String> getParameters(String name) {
        QueryStringDecoder decoder = new QueryStringDecoder(uri);
        return decoder.parameters().get(name);
    }

    public String getUri() {
        return uri;
    }

    public static HandshakeEvent of(WebSocketServerProtocolHandler.HandshakeComplete event) {
        return new HandshakeEvent(event.requestUri(), event.requestHeaders());
    }
}
